package com.sherllinhe.${module}.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
//import com.sherllinhe.common.context.LoginMemberContext;
import com.sherllinhe.common.resp.PageResp;
import com.sherllinhe.common.util.SnowUtil;
import com.sherllinhe.${module}.domain.${Domain};
import com.sherllinhe.${module}.domain.${Domain}Example;
import com.sherllinhe.${module}.mapper.${Domain}Mapper;
import com.sherllinhe.${module}.req.${Domain}QueryReq;
import com.sherllinhe.${module}.req.${Domain}SaveReq;
import com.sherllinhe.${module}.resp.${Domain}QueryResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 功能：
 * 作者：Sherllin He
 * 日期：
 */
@Slf4j
@Service
public class ${Domain}Service {
    @Autowired
    private ${Domain}Mapper ${domain}Mapper;
    // 新增和编辑${tableNameCn}
    public void save(${Domain}SaveReq req){
        DateTime now = DateTime.now();
        ${Domain} ${domain} = BeanUtil.copyProperties(req, ${Domain}.class);

        //判断是新增还是更新
        //${domain}.setMemberId(LoginMemberContext.getId());
        if(ObjUtil.isNull(${domain}.getId())) {
            //新增
            ${domain}.setId(SnowUtil.getSnowflakeNextId());
            ${domain}.setCreateTime(now);
            ${domain}.setUpdateTime(now);
            ${domain}Mapper.insert(${domain});
        }else{
            //更新
            ${domain}.setUpdateTime(now);
            ${domain}Mapper.updateByPrimaryKey(${domain});
        }


    }
    // 分页查询${tableNameCn}列表
    public PageResp<${Domain}QueryResp> queryList(${Domain}QueryReq req){
        ${Domain}Example example = new ${Domain}Example();
        example.setOrderByClause("update_time desc");
        ${Domain}Example.Criteria criteria = example.createCriteria();
        //if(ObjUtil.isNotNull(req.getMemberId())){
            //criteria.andMemberIdEqualTo(req.getMemberId());
        //}

        log.info("查询页码:{}",req.getPage());
        log.info("每页条数:{}",req.getSize());
        PageHelper.startPage(req.getPage(),req.getSize());
        List<${Domain}> ${domain}List = ${domain}Mapper.selectByExample(example);

        PageInfo<${Domain}> pageInfo = new PageInfo<>(${domain}List);
        log.info("总条数:{}", pageInfo.getTotal());
        log.info("总页数:{}", pageInfo.getPages());

        List<${Domain}QueryResp> list = BeanUtil.copyToList(${domain}List, ${Domain}QueryResp.class);

        PageResp<${Domain}QueryResp> pageResp = new PageResp<>();
        pageResp.setList(list);
        pageResp.setTotal(pageInfo.getTotal());

        return pageResp;
    }
    //删除${tableNameCn}
    public void delete(Long id){
        ${domain}Mapper.deleteByPrimaryKey(id);
    }
}
